package com.swf.seed.netty.server.handler;

import org.jboss.netty.buffer.ChannelBuffer;
import static org.jboss.netty.buffer.ChannelBuffers.*;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

@ChannelPipelineCoverage("all") 
public class EchoServerHandler extends SimpleChannelHandler { 
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
    		throws Exception {
    	System.out.println("channelConnected");
    	Channel ch = e.getChannel();
    	ChannelBuffer time = buffer(1);
    	int itime = (int)System.currentTimeMillis()/1000;
    	System.out.println(itime);
    	time.writeInt(itime);
    	  ChannelFuture f = ch.write(itime);
    	  f.addListener(ChannelFutureListener.CLOSE);
    	   f.addListener(new ChannelFutureListener() {  
               public void operationComplete(ChannelFuture future) {  
                   Channel ch = future.getChannel();  
                   ch.close();  
               }  
           });  
    }
 //异常处理
 @Override 
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { 
     e.getCause().printStackTrace();  
      
     Channel ch = e.getChannel();  
     ch.close();  
 }  
}